package com.jcl.recruit.console.core.config;

import com.jcl.core.security.AjaxLogoutSuccessHandler;
import com.jcl.core.security.EntryPointUnauthorizedHandler;
import com.jcl.core.security.RestAccessDeniedHandler;
import com.jcl.core.security.filter.JwtAuthenticationTokenFilter;
import com.jcl.core.security.filter.RbacAuthorityFilter;
import com.jcl.core.security.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @ClassName WebSecurityConfig
 * @Description 安全模块配置
 * @Author yyliu
 * @Date 2018/12/18 15:12
 * @Version 1.0
 **/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private UserDetailService userDetailService;
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    private EntryPointUnauthorizedHandler entryPointUnauthorizedHandler;
    private RestAccessDeniedHandler restAccessDeniedHandler;
    private AjaxLogoutSuccessHandler ajaxLogoutSuccessHandler;
    private PasswordEncoder passwordEncoder;

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public RbacAuthorityFilter rbacAuthorityFilter(){
        return new RbacAuthorityFilter();
    }

    @Autowired
    public WebSecurityConfig(@Qualifier("userDetailService") UserDetailService userDetailService) {
        this.userDetailService = userDetailService;
        this.jwtAuthenticationTokenFilter = new JwtAuthenticationTokenFilter(userDetailService);
        this.entryPointUnauthorizedHandler = new EntryPointUnauthorizedHandler();
        this.restAccessDeniedHandler = new RestAccessDeniedHandler();
        this.ajaxLogoutSuccessHandler = new AjaxLogoutSuccessHandler();
        this.passwordEncoder = new BCryptPasswordEncoder();

    }

    /* *
     * @Author yyliu
     * @Description 处理请求接口
     * @Date 15:20 2018/12/18
     * @Param [http]
     * @return void
     **/
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        httpConfigure(http);
        // httpConfigure2(http);
    }


    private void httpConfigure(HttpSecurity http) throws Exception {
        String[] allowUrls = {"/console/auth/**", "/druid/**"};
        http.csrf().disable()
                // 基于token，所以不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                //.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                // 对于获取token的rest api要允许匿名访问
                .antMatchers(allowUrls).permitAll()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated()
                .and()
                .logout()//默认注销行为为logout
                .logoutUrl("/console/logout")
                .logoutSuccessHandler(ajaxLogoutSuccessHandler)
                .permitAll();
        // 禁用缓存
        http.headers().cacheControl();
        /**
         * 本次 json web token 权限控制的核心配置部分
         * 在 Spring Security 开始判断本次会话是否有权限时的前一瞬间
         * 通过添加过滤器将 token 解析，将用户所有的权限写入本次 Spring Security 的会话
         */

        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().
                authenticationEntryPoint(entryPointUnauthorizedHandler)
                .accessDeniedHandler(restAccessDeniedHandler);
    }

    private void httpConfigure2(HttpSecurity http) throws Exception {
        http.csrf().disable() // 去掉 CSRF
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT，关闭token
                .and()
                .httpBasic().authenticationEntryPoint(entryPointUnauthorizedHandler)
                .and()
                .authorizeRequests()//定义哪些URL需要被保护、哪些不需要被保护
                .anyRequest()//任何请求,登录后可以访问
                .access("@rbacAuthorityFilter.hasPermission(request, authentication)"); // RBAC 动态 url 认证
        //.and()
        //.formLogin()  //开启登录, 定义当需要用户登录时候，转到的登录页面
        //.loginPage("/test/login.html")
        //.loginProcessingUrl("/login")
        //.successHandler(authenticationSuccessHandler) // 登录成功
        //.failureHandler(authenticationFailureHandler) // 登录失败
        //.permitAll()
        //.and()
        //.logout()//默认注销行为为logout
        //.logoutUrl("/logout")
        //.logoutSuccessHandler(logoutSuccessHandler)
        //.permitAll();

        http.exceptionHandling()
                .authenticationEntryPoint(entryPointUnauthorizedHandler)
                .accessDeniedHandler(restAccessDeniedHandler); // 无权访问 JSON 格式的数据
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); // JWT Filter

        // 记住我
        http.rememberMe().rememberMeParameter("remember-me")
                .userDetailsService(userDetailService).tokenValiditySeconds(1000);
    }

    /* *
     * @Author yyliu
     * @Description 处理自定义安全认证
     * @Date 15:20 2018/12/18
     * @Param [auth]
     * @return void
     **/
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder);
    }
}
